package com.chaodriod.common.system;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.chaodriod.common.utils.Utils;

import static android.content.Context.WIFI_SERVICE;

/**
 * Created by annam on 2018/3/20.
 */

public class WifiReceiver extends BroadcastReceiver {

    private WifiStateCallback mWifiStateCallback;
    private long mDelayTime;

    public WifiReceiver(WifiStateCallback wifiStateCallback, long delayTime) {
        mWifiStateCallback = wifiStateCallback;
        mDelayTime = delayTime;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {//这个监听wifi的打开与关闭，与wifi的连接无关
            int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
            switch (wifiState) {
                case WifiManager.WIFI_STATE_DISABLED://禁用
                    mWifiStateCallback.onWifiDisable();
                    break;
                case WifiManager.WIFI_STATE_UNKNOWN://未知
                    mWifiStateCallback.onWifiUnState();
                    break;
                case WifiManager.WIFI_STATE_ENABLED://可用
                    int signalIntensity = getSignalIntensity(context);
                    mWifiStateCallback.onWifiSignalIntensity(signalIntensity, mDelayTime);
                    break;
            }
        }
    }

    public IntentFilter getIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        return filter;
    }

    public int getSignalIntensity(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        return wifiManager.getConnectionInfo().getRssi();
    }

    public interface WifiStateCallback {
        void onWifiDisable();

        void onWifiSignalIntensity(int wifiLevel, long delayTime);

        void onWifiUnState();
    }

    /**
     * 获取wifi强度
     * 0到-50表示信号最好，-50到-70表示信号偏差，小于-70表示最差，有可能连接不上或者掉线，一般Wifi已断则值为-200
     *
     * @return
     */
    public static int getWifiLevel() {
        WifiManager wifiManager = (WifiManager) Utils.getContext().getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        return connectionInfo.getRssi();
    }
}
